package middleware

import (
	"bytes"
	"io/ioutil"
	"log"
	"mytest/initialize/database"
	"mytest/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Operator() gin.HandlerFunc {
	return func(c *gin.Context) {
		var body []byte

		if c.Request.Method != http.MethodGet {
			var err error
			body, err = ioutil.ReadAll(c.Request.Body)
			if err != nil {
				log.Fatal(err)
				//global.GVA_LOG.Error("read body from request error:", zap.Any("err", err))
			} else {
				c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
			}
		}
		record := models.SysOperationRecord{
			Ip:     c.ClientIP(),
			Method: c.Request.Method,
			Path:   c.Request.URL.Path,
			Agent:  c.Request.UserAgent(),
			Body:   string(body),
		}
		c.Next()
		db := database.GetDB()
		err := db.Model(&record).Create(record).Error
		if err != nil {
			log.Fatal(err)
		}

	}
}
